package io.github.biezhi.elves.encrypt;

import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base64;

public enum Base64Encrypt {
	GBK {
		public String getCharset() {
			return CHARSET_GBK;
		}
	},

	UTF8 {
		public String getCharset() {
			return CHARSET_UTF8;
		}
	};
	static final String CHARSET_GBK = "GBK";
	static final String CHARSET_UTF8 = "UTF-8";

	/**
	 * 获取编码
	 */
	public String getCharset() {
		throw new AbstractMethodError();
	}

	/**
	 * base64编码
	 */
	public String encodeBase64(String str) throws UnsupportedEncodingException {
		try {
			String charset = getCharset();
			byte[] b = Base64.encodeBase64(str.getBytes(charset));
			return new String(b, charset);
		} catch (UnsupportedEncodingException e) {
			throw e;
		}
	}
	
	/**
	 * base64编码
	 */
	public String encodeBase64(byte[] str) throws UnsupportedEncodingException {
		try {
			String charset = getCharset();
			byte[] b = Base64.encodeBase64(str);
			return new String(b, charset);
		} catch (UnsupportedEncodingException e) {
			throw e;
		}
	}

	/**
	 * base64解码
	 */
	public String decodeBase64(String str) throws UnsupportedEncodingException {
		try {
			String charset = getCharset();
			byte[] b = Base64.decodeBase64(str.getBytes(charset));
			return new String(b, charset);
		} catch (UnsupportedEncodingException e) {
			throw e;
		}
	}
	
	/**
	 * base64解码
	 */
	public byte[] decodeBase64ToByte(String str) throws UnsupportedEncodingException {
		try {
			String charset = getCharset();
			return Base64.decodeBase64(str.getBytes(charset));
		} catch (UnsupportedEncodingException e) {
			throw e;
		}
	}
	
	/**
	 * 简单的字符串加密 Decryption
	 */
	public static String simpleEncry(String s) {
		String src = "abcdefghijklmnopqrstuvwxyz_-;012345+6789ABCDEFGHIJKLMNOPQRSTUVWXYZ@.=";
		String dest ="v-Wkn8UFzf@IJ6KHw;PM34VrX5NiljOx=dS bc1Y2up7CtaqD.EG_e0LsQmABygRTohZ9";

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < s.length(); i++) {
			sb.append(dest.charAt(src.indexOf(s.charAt(i))));
		}
		return sb.toString();
	}

	//解密
	public static String simpleDecry(String s) {
		String src = "v-Wkn8UFzf@IJ6KHw;PM34VrX5NiljOx=dS bc1Y2up7CtaqD.EG_e0LsQmABygRTohZ9";
		String dest ="abcdefghijklmnopqrstuvwxyz_-;012345+6789ABCDEFGHIJKLMNOPQRSTUVWXYZ@.=";

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < s.length(); i++) {
			sb.append(dest.charAt(src.indexOf(s.charAt(i))));
		}
		return sb.toString();
	}
}